//
//  NetWorkManager.m
//  SmartTalk
//
//  Created by 陈勃 on 14-12-22.
//  Copyright (c) 2014年 gameabc. All rights reserved.
//

#import "NetWorkManager.h"
#import "AsyncSocket.h"
#import "NSObject+JSON.h"
#import "TTDefines.h"
#import "NetWorkQueue.h"
@interface NetWorkManager ()
{
    AsyncSocket *socket;
    NSMutableArray *cmdArray;
    NSLock * _transIdIndexLock;
    long _transIdIndex;
}
@end
@implementation NetWorkManager
SYNTHESIZE_SINGLETON_FOR_CLASS(NetWorkManager)
#pragma mark AsyncSocketDelegate
- (instancetype)init
{
    self = [super init];
    if (self) {
       
        _transIdIndexLock = [[NSLock alloc]init];
        [_transIdIndexLock lock];
        _transIdIndex = 0;
        [_transIdIndexLock unlock];
        
    }
    return self;
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"willDisconnectWithError");
    [self reconnect];
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"connect %@ port %d success",host,port);
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"receive data %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    [sock readDataWithTimeout:-1 tag:0];
    NSError *error = nil;
    NSDictionary *rspDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    int action = [[rspDic objectForKey:@"action"] intValue];
    CmdProcessor *processoring = nil;
    for (CmdProcessor *processor in cmdArray) {
        if ([processor handle:action info:rspDic]) {
            processoring = processor;
            break;
        }
    }
    if (processoring) {
         [cmdArray removeObject:processoring];
    }
}


-(void)handleLogin:(NSDictionary *)rspDic
{
    _senderid = [[rspDic objectForKey:@"userid"] intValue];
}

-(void)handleFriendList:(NSDictionary *)rspDic
{
    NSArray *array = [rspDic objectForKey:@"data"];

}

-(void)reconnect
{
    NSError *error = nil;
   
    socket =  [[AsyncSocket alloc] initWithDelegate:self];
    [socket connectToHost:@"192.168.1.100" onPort:1889 error:&error];
    if (error) {
        NSLog(@"error %@",error);
    }
}

-(void)connect
{
    
    socket =  [[AsyncSocket alloc] initWithDelegate:self];
    NSError *error = nil;
    [socket connectToHost:@"192.168.1.100" onPort:1889 error:&error];
    if (error) {
        NSLog(@"error %@",error);
    }
    [self sendKeepAlive];
}


-(void)excuteCmd:(CmdProcessor *)processor
{
    [self sendContent:[processor.reqDict JSONRepresentation]];
    if (!cmdArray) {
        cmdArray = [NSMutableArray array];
    }
    [cmdArray  addObject:processor];
}

- (uint64_t)getLongTransIdIndex
{
    uint64_t index = 0;
    [_transIdIndexLock lock];
    index = _transIdIndex;
    _transIdIndex++;
    [_transIdIndexLock unlock];
    return index;
}

-(void)sendKeepAlive
{
    NSDictionary *dic  = @{@"action":@(TTNetActionTypeHeart)};
    [self sendContent:[dic JSONRepresentation]];
}




-(void)sendContent:(NSString *)content
{
    [socket writeData:[content dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:101];
}


-(void)sendMessageWithInfo:(NSDictionary *)info to:(int)touserid
{
    NSDictionary *dic = @{@"action":@(TTNetActionTypeHeart),
                          @"message":info,
                          @"touserid":@(touserid),
                          @"fromuserid":@(_senderid)};
    [self sendContent:[dic JSONRepresentation]];
}


-(void)sendMessageWithInfo:(NSDictionary *)info data:(NSData *)fileData to:(int)userid
{
    //TODO
}

@end
